<?php

namespace Iwesen\Sem\Track\Advertisers;

class Request
{
    public function _request($url,$headers=[],$post=[],$form=false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        //curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');

        if ($post) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, !empty($headers)?$headers:array(
                'Content-Type: application/json; charset=utf-8'
            )
            );
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $form?http_build_query($post):json_encode($post));
        }else{
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
            if($headers){
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            }

        }
        $sResult = curl_exec($curl);
        if($sError=curl_error($curl)){
           return $sError;
        }
        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        curl_close($curl);
        if($sResult){
            return $sResult;
        }
        //部分渠道根据响应状态码判断是否成功
        return json_encode(['httpCode'=>$httpCode]);
    }
}